
export class Hub {
  constructor(){
    this.connectionId='';
    this.connect=null;
  }
  connection(url,connectionId){
    url += (url.indexOf("?") < 0 ? "?" : "&") + ("id=" + connectionId);
    url = url.replace(/^http/, "ws");

    this.connect= wx.connectSocket({
      url: url,
      method: "get",
      success(res){
        console.log(res);
      }
      ,fail(err){
        // console.log(err)
      }
    })
    this.connect.onOpen(res=>{
      console.log(`websocket connectioned to ${url}`);
      // this.onOpen(res);
    })

    return this.connectionId;

  }
  invoke(method,args){
    if(this.connection){

    }
  }
  start(url, queryString) {
    var _this=this;
    return new Promise((resolve, reject)=>{

      var negotiateUrl = url + "/negotiate";
      if (queryString) {
        for (var query in queryString) {
          negotiateUrl += (negotiateUrl.indexOf("?") < 0 ? "?" : "&") + (`${query}=` + encodeURIComponent(queryString[query]));
        }
      }
      wx.request({
        url: negotiateUrl,
        method: "post",
        async: false,
        success (res) {         
          resolve(_this.connection(url,res.data.connectionId))
        },
        fail (err) {
          reject(err)
        }
      });    
    })
  }
}